

var md5Utils = require('./MD5.js')   

function raw1(args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key] = args[key];
  });

  var str = '';
  for (var k in newArgs) {
    str += '&' + k + '=' + newArgs[k];
  }
  str = str.substr(1);
  return str;
};

function paysignjs(data) {
  var ret = {
    appId: data.appid,
    nonceStr: data.nonce_str,
    package: data.prepay_id,
    signType: 'MD5',
    timeStamp: data.timeStamp
  };
  var str = raw1(ret);
  // str = str + '&key=' + key;
  return md5Utils.hexMD5(str)
  // return cryptoMO.createHash('md5').update(str).digest('hex');
};


function pay(data, callBack) {
  // let sign = paysignjs(data)
  wx.requestPayment({
    'timeStamp': data.timeStamp,
    'nonceStr': data.nonce_str,
    'package': 'prepay_id=' + data.prepay_id, // 
    'signType': 'MD5',
    'paySign': data.paySign,
    'success': function (res) {
      callBack(null, res)
    },
    'fail': function (res) {
      callBack(res)
    }
  })
}
module.exports = {
  pay: pay
}